function getMenuList(checkedkeys){
    let newArr = []
    checkedkeys.forEach(item => {
        const length = item.split("_").length-1;
        const reg = /_/g
        for (let i = 0 ; i < length ; i++){
            const index  =  reg.exec(item).index;
            newArr.push(item.slice(0 , index))
        }
        newArr.push(item)
    })
    return newArr;
} 
//将用户菜单权限从路由表当中过滤出来
function filterRoute(menuList,routerAsync){
   const userRoute = routerAsync.filter(item => {
    if(menuList.includes(item.name)){
        if(item.children && item.children.length){
            item.children = filterRoute(menuList,item.children)
        }
        return true;
    }
   })
   return userRoute;
}



import routerAsync from "../../router/routerAsync.js";

export default {
    namespaced:true,
    //数据源
    state(){
        return{
            userInfo:JSON.parse(localStorage.getItem("userInfo")) || '',
        }
    },
    //直接操作数据源
    mutations:{
        SET_USERINFO(state,payload){
            state.userInfo = payload;
            localStorage.setItem("userInfo",JSON.stringify(payload))          
        }
    },
    getters:{
        //将用户的菜单数据加工
        getMenuInfo(state){
            if(state.userInfo.role == 2){
                return routerAsync
            }else{
                const menuList = [...new Set(getMenuList(state.userInfo.checkedkeys))];
                const userRoute = filterRoute(menuList,routerAsync)
                return userRoute;
            }
            
        },
        getcheckedkeys(state){
            return state.userInfo.checkedkeys
        },
        getRole(state){
            return state.userInfo?.role;
        },



        //返回用户得token
        getToken(state){
            // if(state.userInfo){
            //     return state.userInfo.token
            // }
            return state.userInfo?.token
        }
    }
}